package cn.edu.heuet.bnve.fragment;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;

import android.annotation.SuppressLint;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.xuexiang.xui.widget.button.SmoothCheckBox;
import com.xuexiang.xui.widget.guidview.GuideCaseQueue;
import com.xuexiang.xui.widget.guidview.GuideCaseView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.edu.heuet.bnve.activity.SettingActivity.TodoSettingActivity;
import cn.edu.heuet.bnve.utils.SharepreferencesUtilSystemSettings;
import cn.edu.heuet.bnve.view.RecyclerItemClickListener;
import cn.edu.heuet.bnve.model.Schedule;
import cn.edu.heuet.bnve.activity.ScheduleActivity.ScheduleDetailActivity;
import cn.edu.heuet.bnve.adapter.ScheduleAdapter;
import cn.edu.heuet.bnve.base.fragment.BaseFragment;
import cn.edu.heuet.bnve.R;
import cn.edu.heuet.bnve.database.ScheduleDao;
import cn.edu.heuet.bnve.databinding.FragmentScheduleBinding;
import cn.edu.heuet.bnve.view.group.GroupItemDecoration;
import cn.edu.heuet.bnve.view.group.GroupRecyclerView;

public class ScheduleFragment extends BaseFragment implements
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnCalendarLongClickListener,
        CalendarView.OnMonthChangeListener,
        CalendarView.OnYearChangeListener,
        CalendarView.OnWeekChangeListener,
        CalendarView.OnViewChangeListener,
        CalendarView.OnCalendarInterceptListener,
        CalendarView.OnYearViewChangeListener,
        View.OnClickListener {

    private ScheduleViewModel mViewModel;
    private FragmentScheduleBinding binding;

    private ScheduleDao scheduleDao;
    private List<Schedule> schedulesCur;
    private List<Schedule> schedulesAll;
    private TextView mTextMonthDay;
    private TextView mTextYear;
    private TextView mTextLunar;
    private TextView mTextCurrentDay;
    private CalendarView mCalendarView;
    private int mYear;
    private CalendarLayout mCalendarLayout;
    private GroupRecyclerView mRecyclerView;

    private int calenderStartDay =0;
    private int monthViewModel =0;
    private int gestureModel =0;

    // 日历拓展功能弹出
    private AlertDialog mMoreDialog;

    public static ScheduleFragment newInstance() {
        return new ScheduleFragment();
    }


    protected  int getLayoutId(){
        return  R.layout.fragment_schedule;
    }

    public  void initView(){
        if(mRootView!=null){
            binding= DataBindingUtil.bind(this.mRootView);
//            setStatusBarDarkMode();
            mTextMonthDay = binding.tvMonthDay;
            mTextYear = binding.tvYear;
            mTextLunar = binding.tvLunar;
            mCalendarView = binding.calendarView;
            mTextCurrentDay = binding.tvCurrentDay;
            //点击会展开所有月份
            mTextMonthDay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!mCalendarLayout.isExpand()) {
                        mCalendarLayout.expand();
                        return;
                    }
                    mCalendarView.showYearSelectLayout(mYear);
                    mTextLunar.setVisibility(View.GONE);
                    mTextYear.setVisibility(View.GONE);
                    mTextMonthDay.setText(String.valueOf(mYear));
                }
            });
            binding.flCurrent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCalendarView.scrollToCurrent();
                }
            });
            mCalendarLayout = binding.calendarLayout;
            mCalendarView.setOnCalendarSelectListener(this);
            mCalendarView.setOnYearChangeListener(this);
            mTextYear.setText(String.valueOf(mCalendarView.getCurYear()));
            mYear = mCalendarView.getCurYear();
            mTextMonthDay.setText(mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日");
            mTextLunar.setText("今日");
            mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));

            mCalendarLayout.setOnDragListener(new View.OnDragListener() {
                @Override
                public boolean onDrag(View view, DragEvent dragEvent) {
                    return false;
                }
            });

        }
        else{
            Log.i("aaa","mRoot_null");
        }

        mCalendarView.setOnYearChangeListener(this);
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnMonthChangeListener(this);
        mCalendarView.setOnCalendarLongClickListener(this, true);
        mCalendarView.setOnWeekChangeListener(this);
        mCalendarView.setOnYearViewChangeListener(this);
        mCalendarView.setThemeColor(getResources().getColor(R.color.red),getResources().getColor(R.color.red));

        //end
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    protected  void initData(){

        scheduleDao = new ScheduleDao(mContext);

        schedulesCur = scheduleDao.getDataByDay(mCalendarView.getSelectedCalendar());

//        schedulesAll = scheduleDao.getAll();
        initProgress();


        mRecyclerView = binding.recyclerView;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new GroupItemDecoration<String, Schedule>());
        mRecyclerView.setAdapter(new ScheduleAdapter(mContext,schedulesCur));
        mRecyclerView.notifyDataSetChanged();


    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    protected void initEvent(){
        //recycler点击事件
        mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(mContext, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(schedulesCur.get(position).getType()!=-1&&schedulesCur.get(position).getType()!=2) {
                    Intent intent = new Intent(mContext, ScheduleDetailActivity.class);
                    intent.putExtra("schedule", schedulesCur.get(position));
                    startActivity(intent);
                }
            }
            @Override
            public void onLongClick(View view, int posotion) {
                if(schedulesCur.get(posotion).getType()==0||schedulesCur.get(posotion).getType()==1){
                    SmoothCheckBox checkBox = view.findViewById(R.id.cb_complete);
                    Schedule schedule = schedulesCur.get(posotion);
                    if(checkBox.isChecked()){
                        checkBox.setChecked(false,true);
                        schedule.setIsComplete(0);
                    }
                    else{
                        checkBox.setChecked(true,true);
                        schedule.setIsComplete(1);
                    }
                    scheduleDao.updateDataById(schedule.getId(),schedule);
                    initProgress();
                }
            }
        }));
        binding.ivSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TodoSettingActivity.show(mContext);
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        mTextLunar.setVisibility(View.VISIBLE);
        mTextYear.setVisibility(View.VISIBLE);
        mTextMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        mTextYear.setText(String.valueOf(calendar.getYear()));
        mTextLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();


        schedulesCur = scheduleDao.getDataByDay(calendar);

        mRecyclerView.setAdapter(new ScheduleAdapter(mContext,schedulesCur));
    }

    @Override
    public void onYearChange(int year) {
        mTextMonthDay.setText(String.valueOf(year));
    }

    /*
生成Fragment时改变menu布局
 */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
//        menu.clear();
//        inflater.inflate(R.menu.menu_schedule,menu);
    }


//    @Override
//    /**menu监听事件*/
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//
//            case R.id.action_change_calender:
//
//                break;
//            case R.id.action_add:
//                if (getActivity() instanceof MainActivity) {
//                    MainActivity mainActivity = (MainActivity) getActivity();
//                    mainActivity.toggle();
//                }
//                break;
//        }
//
//        return false;
//    }

    @Override
    public boolean onCalendarIntercept(Calendar calendar) {
        return false;
    }

    @Override
    public void onCalendarInterceptClick(Calendar calendar, boolean isClick) {

    }

    @Override
    public void onCalendarLongClickOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarLongClick(Calendar calendar) {

    }

    @Override
    public void onMonthChange(int year, int month) {

    }

    @Override
    public void onViewChange(boolean isMonthView) {

    }

    @Override
    public void onWeekChange(List<Calendar> weekCalendars) {

    }

    @Override
    public void onYearViewChange(boolean isClose) {

    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onStart() {
        super.onStart();
        if(scheduleDao!=null) {
            schedulesCur = scheduleDao.getDataByDay(mCalendarView.getSelectedCalendar());
            mRecyclerView.setAdapter(new ScheduleAdapter(mContext, schedulesCur));
            schedulesAll = scheduleDao.getAll();
            initProgress();
            setCalenderStartDay();
            setMonthViewModel();
            setCalenderGestureModel();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initProgress(){
        boolean i = SharepreferencesUtilSystemSettings.getValue(mContext, "calender_progress_visible", true);
        if(i) {
            //分组
            schedulesAll = scheduleDao.getAll();
            Map<String, List<Schedule>> mapList=schedulesAll.stream().collect(Collectors.groupingBy(t -> t.getYearMonthDay()));
            Map<String, Calendar> mapCalender = new HashMap<>();
            for (String key:mapList.keySet()){
                int count = mapList.get(key).size();
                int completeCount = 0;
                for (Schedule schedule:mapList.get(key)){
                    if (schedule.getIsComplete() == 1){
                        completeCount++;
                    }
                }
                int value = (int) completeCount*100/count;
                mapCalender.put(getSchemeCalendar(mapList.get(key).get(0).getYear(), mapList.get(key).get(0).getMonth(), mapList.get(key).get(0).getDay(), 0xFF40db25, value+"").toString(),
                        getSchemeCalendar(mapList.get(key).get(0).getYear(), mapList.get(key).get(0).getMonth(), mapList.get(key).get(0).getDay(), 0xFF40db25, value+""));
            }
            //此方法在巨大的数据量上不影响遍历性能，推荐使用
            mCalendarView.setSchemeDate(mapCalender);
        }
        else{
            Map<String, Calendar> mapCalender = new HashMap<>();
            mCalendarView.setSchemeDate(mapCalender);
        }
    }

    private void setCalenderStartDay() {
        int value = SharepreferencesUtilSystemSettings.getValue(mContext, "calender_start_day", 0);
        if (value != calenderStartDay) {
            switch (value) {
                case 0:
                    mCalendarView.setWeekStarWithSun();
                    break;
                case 1:
                    mCalendarView.setWeekStarWithMon();
                    break;
                case 2:
                    mCalendarView.setWeekStarWithSat();
                    break;

            }
            calenderStartDay = value;
        }
    }

    private void setMonthViewModel() {
        int value = SharepreferencesUtilSystemSettings.getValue(mContext, "calender_month_view_model", 0);
        if (value != monthViewModel) {
            switch (value) {
                case 0:
                    mCalendarView.setAllMode();
                    break;
                case 1:
                    mCalendarView.setOnlyCurrentMode();
                    break;
                case 2:
                    mCalendarView.setFixMode();
                    break;
            }
            monthViewModel = value;
        }
    }

    private void setCalenderGestureModel(){
        int value = SharepreferencesUtilSystemSettings.getValue(mContext, "calender_gesture_model", 0);
        if(value!=gestureModel){
            mCalendarLayout.setGestureMode(value);
            gestureModel=value;
        }
    }







}